package cn.wxManage.common.service.impl;

import cn.common.common.model.ServerResponse;
import cn.wxManage.common.dao.DistrictInfoMapper;
import cn.wxManage.common.service.IUtilService;
import net.coobird.thumbnailator.Thumbnailator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

/**
 * Created by Zhang on 2018/12/11.
 */
@Service
public class UtilServiceImpl implements IUtilService {
    @Autowired
    DistrictInfoMapper districtInfoMapper;
    @Override
    public ServerResponse<?> uploadImg(String path, MultipartFile multipartFile) {
        String fileName;
        try {
            path = "/home/img/" + path;
            //获取上传文件名
            String originalFilename=multipartFile.getOriginalFilename();
            String uploadFileSuffix = originalFilename.substring(
                    originalFilename.lastIndexOf('.'));
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            fileName = UUID.randomUUID() + uploadFileSuffix;
            ByteArrayInputStream in= reduceImg(multipartFile.getInputStream());
            FileOutputStream out=new FileOutputStream(new File(path+ fileName));
            byte [] bytes=new byte[10240];
            int len;
            while((len=in.read(bytes))!=-1){
                out.write(bytes, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("上传失败");
        }
        return ServerResponse.createBySuccessMessage(fileName);
    }

    @Override
    public ServerResponse<?> getDistrictList(String keywords) {
        return ServerResponse.createBySuccess(districtInfoMapper.getDistrictList(keywords));
    }

    private ByteArrayInputStream reduceImg(InputStream in){
        ByteArrayInputStream is;
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Thumbnailator.createThumbnail(in, os, 400, 400);
            is = new ByteArrayInputStream(os.toByteArray());
            in.close();
            os.close();
        } catch (IOException e) {
            return null;
        }
        return is;
    }
}
